/**
 * 日期时间工具类
 */

// 格式化日期时间
export const formatDateTime = (
  date: Date | string | number,
  format: string = "YYYY-MM-DD HH:mm:ss"
): string => {
  const d = new Date(date);
  const year = d.getFullYear();
  const month = d.getMonth() + 1;
  const day = d.getDate();
  const hour = d.getHours();
  const minute = d.getMinutes();
  const second = d.getSeconds();

  format = format.replace(/YYYY/g, year.toString());
  format = format.replace(/MM/g, month.toString().padStart(2, "0"));
  format = format.replace(/DD/g, day.toString().padStart(2, "0"));
  format = format.replace(/HH/g, hour.toString().padStart(2, "0"));
  format = format.replace(/mm/g, minute.toString().padStart(2, "0"));
  format = format.replace(/ss/g, second.toString().padStart(2, "0"));

  return format;
};

// 格式化为相对时间
export const formatRelativeTime = (date: Date | string | number): string => {
  const now = new Date().getTime();
  const target = new Date(date).getTime();
  const diff = now - target;

  // 小于1分钟
  if (diff < 60 * 1000) {
    return "刚刚";
  }
  // 小于1小时
  if (diff < 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 1000))}分钟前`;
  }
  // 小于24小时
  if (diff < 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 60 * 1000))}小时前`;
  }
  // 小于30天
  if (diff < 30 * 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`;
  }
  // 小于12个月
  if (diff < 12 * 30 * 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (30 * 24 * 60 * 60 * 1000))}个月前`;
  }
  // 大于12个月
  return `${Math.floor(diff / (12 * 30 * 24 * 60 * 60 * 1000))}年前`;
};

// 获取日期范围
export const getDateRange = (days: number): [Date, Date] => {
  const end = new Date();
  const start = new Date();
  start.setTime(start.getTime() - 3600 * 1000 * 24 * days);
  return [start, end];
};

// 判断是否为同一天
export const isSameDay = (
  date1: Date | string | number,
  date2: Date | string | number
): boolean => {
  const d1 = new Date(date1);
  const d2 = new Date(date2);
  return (
    d1.getFullYear() === d2.getFullYear() &&
    d1.getMonth() === d2.getMonth() &&
    d1.getDate() === d2.getDate()
  );
};

// 获取某月的天数
export const getDaysInMonth = (year: number, month: number): number => {
  return new Date(year, month, 0).getDate();
};

// 获取某月的第一天是星期几
export const getFirstDayOfMonth = (year: number, month: number): number => {
  return new Date(year, month - 1, 1).getDay();
};
